#include "state_proc.h"

byte	plc_state = PlcIdel;
byte 	plc_sending_char = 0xFF;   
byte 	fail_counter = 0;
bool 	send_flag = false;
bool 	plc_sending_success = true;
		 
void plc_send_proc()
{
	switch(plc_state)
	{
	case PlcIdel:
		//plc_state = PlcIntial;
		break;
	case PlcIntial:
		plc_intial(0x11);
		plc_state = PlcSendByte;
		send_flag = 0;
		uart_put_send_msg(0x01);
		break;
	case PlcSendByte:
		if(plc_sending_success && (!plc_has_send_data()))
		{
			plc_state = PlcSendEndFrame;
			uart_put_send_msg(0x23);
			break;
		}		
		if(plc_sending_success)
		{	
			if(plc_has_send_data())
			{	
				plc_sending_char = plc_get_send_msg();	
				if(plc_sending_char != 0xFF) 
				{
					plc_sending_success = plc_send_byte(plc_sending_char);		
					uart_put_send_msg(plc_sending_char);		
				}

				uart_put_send_msg(0x02);		
				
				
				send_flag = 1;
			}		
		}	
		else
		{			
			uart_put_send_msg(0xF2);					
		}
		break;
	case PlcSendEndFrame:
		if(PlcSendFrameEnd())
		{
			plc_state = PlcSendFinishCheck;
			uart_put_send_msg(0x03);
		}		
		else
		{	
			plc_state = PlcSendFailed;
			uart_put_send_msg(0xF3);
		}
		break;
	case PlcSendFinishCheck:
		if(PlcSendSuccess())
		{
			plc_state = PLCSendSuccess;
			uart_put_send_msg(0x04);
		}
		else
		{
			uart_put_send_msg(0xF4);

			fail_counter++;
			if(fail_counter > 9)
			{	
				fail_counter = 0;
				plc_state = PlcSendFailed;				
			}
		}
		break;
	case PlcSendFailed:
		disable_plc();
	default:		
		break;		
	}

	return;
}



